<template>
  <Page class="bg-[#f5f7fa] min-h-screen">

    <!-- 顶部蓝色渐变背景 -->
    <view
      class="fixed top-0 left-0 w-full z-[3] h-[250rpx] bg-gradient-to-b from-[#2196F3] to-[#6ec6ff] rounded-b-[40rpx]"
    ></view>

    <!-- 吸顶标题与导航栏 -->
    <view class="sticky top-0 z-30 w-[750rpx] box-border pt-[32rpx] pb-[0] bg-transparent">
      <PageHeader title="" :showBack="true" :onlyBack="true"/>
      <view
        class="text-[36rpx] w-full z-1 events-none text-center font-bold text-white mb-[24rpx] flex justify-center items-center"
      >
        <text>我的发布</text>
        <!-- <nut-button
          size="small"
          type="info"
          shape="round"
          @click="handleNewPublish"
        >
          <template #icon>
            <IconFont name="plus" size="20" class="mr-1" />
          </template>
        </nut-button> -->
      </view>

      <!-- 导航选项：日结、悬赏、招聘 -->
      <view
        class="flex overflow-x-auto gap-x-[18rpx] py-[10rpx] px-[32rpx] scrollbar-hide"
      >
        <view
          v-for="(nav, index) in navOptions"
          :key="index"
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap flex-shrink-0"
          :class="
            activeNav === index
              ? 'bg-gradient-to-r from-[#2196F3] to-[#6ec6ff] text-white font-bold shadow-md border-[#2196F3]'
              : 'bg-white/80 text-[#2196F3]/80 hover:bg-white'
          "
          @click="activeNav = index"
        >
          {{ nav }}
        </view>
      </view>
    </view>

    <!-- 内容区 -->
    <view class="pt-[20rpx] pb-[32rpx] px-[0] mt-[30rpx]">
      <view class="p-[24rpx_32rpx] flex flex-col gap-y-[28rpx]">
        <!-- 空状态 -->
        <EmptyState
          v-if="currentItems.length === 0"
          :type="activeNav"
          @publish="handleNewPublish"
        />

        <!-- 发布内容列表（引入组件） -->
        <PublishedItem
          v-for="(item, index) in currentItems"
          :key="item.id"
          :item="item"
          :type="activeNav"
          @click="handleItemClick"
          @viewDetails="handleViewDetails"
          @delete="handleDelete"
        />
      </view>

      <!-- 加载更多 -->
      <view
        v-if="currentItems.length > 0"
        class="flex justify-center mt-[20rpx] mb-[30rpx]"
      >
        <nut-button
          size="small"
          type="default"
          class="border-[#2196F3] text-[#2196F3] bg-transparent rounded-[20rpx] px-[36rpx] py-[10rpx] text-[24rpx] font-medium hover:bg-[#e3f2fd] transition-all duration-200 flex items-center justify-center"
          @click="handleLoadMore"
        >
          <!-- <IconFont name="load-more" size="20" class="mr-[10rpx]" /> -->
          <span>加载更多</span>
        </nut-button>
      </view>
    </view>
  </Page>
</template>

<script setup >
import { ref, computed, onMounted, watch } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { Button as nutButton } from "@nutui/nutui-taro";
// 引入封装的组件
import PublishedItem from "./components/PublishedItem.vue";
import EmptyState from "./components/EmptyState.vue";
import { post } from "@/utils/request";
//import {number} from "unocss-preset-weapp/dist/utils";

// 导航选项
const navOptions = ["日结", "悬赏", "招聘"];
const activeNav = ref(0);
const badgeCounts = ref([2, 1, 0]); // 导航未处理事项数量

//定义获取数据的格式
/*interface OrderColumn {
      member_id: null,
      create_time: null,
      time_frame: null,
      pay_number: null,
      position_name: null,
      description: null,
      type: null,
      experience: null,
      salary: null,
      number: null,
      pay_status: null,
      update_time: null,
      name: null,
      corporate_name: null,
      location: null,
      id: null,
      deadline: null,
      status: null
}

interface OrderItem {
  columns: OrderColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}*/


// 发布内容数据（按类型区分）
const publishedItems = ref({
  // 0: 日结类
  0: [
    /*{
      member_id: null,
      create_time: null,
      time_frame: null,
      pay_number: null,
      position_name: null,
      description: null,
      type: null,
      experience: null,
      salary: null,
      number: null,
      pay_status: null,
      update_time: null,
      name: null,
      corporate_name: null,
      location: null,
      id: null,
      deadline: null,
      status: null
    }
    /*{
      id: "d1",
      title: "超市临时导购员（周末2天）",
      status: "新发布",
      statusClass: "bg-[#e6f7ff] text-[#1890ff]",
      desc: "负责食品区域导购，介绍促销活动，引导顾客购买，要求热情开朗，有相关经验者优先，日结薪资180元+提成",
      publishTime: "今天 09:15",
      deadline: "本周日 22:00",
      endTime: "",
      amount: "￥180/天",
      tags: ["导购", "日结", "周末"],
      applyCount: 23,
      progress: 0,
      hasPhase: false,
      isHot: true,
    },
    {
      id: "d2",
      title: "展会协助人员（3天）",
      status: "执行中",
      statusClass: "bg-[#f6ffed] text-[#52c41a]",
      desc: "负责展会现场物料整理、观众引导、资料发放，工作时间9:00-17:30，包午餐，日结200元，需连续工作3天",
      publishTime: "3天前",
      deadline: "后天 18:00",
      endTime: "",
      amount: "￥200/天",
      tags: ["展会", "协助", "日结"],
      applyCount: 0,
      progress: 40,
      hasPhase: false,
      isHot: false,
    },*/
  ],
  // 1: 悬赏类
  1: [
    /*{
      id: "x1",
      title: "公司宣传册设计",
      status: "执行中",
      statusClass: "bg-[#f6ffed] text-[#52c41a]",
      desc: "设计企业宣传册封面及内页版式，需体现科技感与专业性，提供3版方案选择，选中后修改至满意",
      publishTime: "5天前",
      deadline: "10天后",
      endTime: "",
      amount: "￥1500",
      tags: ["平面设计", "宣传册", "企业"],
      applyCount: 15,
      progress: 30,
      hasPhase: true,
      currentPhase: "内容排版",
      phaseStatus: "进行中",
      phaseAmount: "￥800",
      phaseDeadline: "5天后 18:00",
      isHot: false,
    },
    {
      id: "x2",
      title: "小程序功能优化",
      status: "已结束",
      statusClass: "bg-[#fff5f5] text-[#ff4d4f]",
      desc: "优化电商小程序加载速度与支付流程，解决卡顿问题，要求3天内完成，验收合格后立即付款",
      publishTime: "2周前",
      deadline: "1周前",
      endTime: "6天前",
      amount: "￥1200",
      tags: ["小程序", "优化", "技术"],
      applyCount: 8,
      progress: 100,
      hasPhase: false,
      isHot: false,
    },
    {
      id: "x3",
      title: "产品文案撰写（中英双语）",
      status: "新发布",
      statusClass: "bg-[#e6f7ff] text-[#1890ff]",
      desc: "为智能手表撰写产品介绍文案，需突出健康监测功能和续航优势，提供中英双语版本",
      publishTime: "昨天 10:20",
      deadline: "3天后",
      endTime: "",
      amount: "￥800",
      tags: ["文案", "中英双语", "产品"],
      applyCount: 9,
      progress: 0,
      hasPhase: false,
      isHot: true,
    },*/
  ],
  // 2: 招聘类
  2: [
    /*{
      id: "z1",
      title: "兼职新媒体运营（长期）",
      status: "新发布",
      statusClass: "bg-[#e6f7ff] text-[#1890ff]",
      desc: "负责公众号与小红书内容发布，每周3篇原创，要求熟悉美妆领域，能独立完成选题、撰写与排版",
      publishTime: "昨天 14:30",
      deadline: "1个月后",
      endTime: "",
      amount: "￥3000/月",
      tags: ["新媒体", "兼职", "美妆"],
      applyCount: 27,
      progress: 0,
      hasPhase: false,
      isHot: true,
    },
    {
      id: "z2",
      title: "前端开发工程师（全职）",
      status: "执行中",
      statusClass: "bg-[#f6ffed] text-[#52c41a]",
      desc: "负责公司官网和管理系统前端开发，要求3年以上React经验，熟悉TypeScript，能独立完成组件设计",
      publishTime: "1周前",
      deadline: "持续招聘",
      endTime: "",
      amount: "￥15k-25k/月",
      tags: ["前端", "React", "全职"],
      applyCount: 42,
      progress: 60,
      hasPhase: false,
      isHot: false,
    },
    {
      id: "z3",
      title: "周末英语教师（兼职）",
      status: "已结束",
      statusClass: "bg-[#fff5f5] text-[#ff4d4f]",
      desc: "为6-12岁儿童提供英语口语教学，要求英语流利，有教学经验，周末上课，每次2小时",
      publishTime: "3周前",
      deadline: "1周前",
      endTime: "3天前",
      amount: "￥200/课时",
      tags: ["教育", "英语", "兼职"],
      applyCount: 15,
      progress: 100,
      hasPhase: false,
      isHot: false,
    },*/
  ],
});

// 当前显示的内容
const currentItems = computed(() => {
  //console.log("publishedItems",publishedItems)
  return publishedItems.value[activeNav.value] || [];
});

watch(activeNav, () => {
  getTaskList();
});
const getListUrl = () => {
  //日结
  if (activeNav.value === 0) {
    return "/recruitmentDaily/myRelease";
  }

  //悬赏
  if (activeNav.value === 1) {
    return "/task/myRelease";
  }

  //招聘
  if (activeNav.value === 2) {
    return "/recruitment/myRelease";
  }
};

// 处理发布新内容
const handleNewPublish = () => {
  const typeMap = ["daily", "reward", "recruit"];
  Taro.navigateTo({
    url: `/pages/publish/new?type=${typeMap[activeNav.value]}`,
  }).catch((err) => {
    console.error("跳转发布页失败：", err);
  });
};

// 处理内容项点击
const handleItemClick = (item) => {
  Taro.navigateTo({
    url: `/pages/publish/detail?id=${item.id}&type=${activeNav.value}`,
  }).catch((err) => {
    console.error("跳转详情页失败：", err);
  });
};

// 处理管理按钮点击
const handleViewDetails = (item) => {
  Taro.navigateTo({
    url: `/pages/post/applicants?taskId=${item.id}&type=${activeNav.value}`,
  }).catch((err) => {
    console.error("跳转申请用户列表失败：", err);
  });
};

// 处理删除按钮点击
const handleDelete = (item) => {
  console.log("删除内容：", item);
  Taro.showModal({
    title: "确认删除",
    content: "确定要删除该任务吗？",
    success: (res) => {
      if (res.confirm) {
        post("/task/del", {
          id: item.id,
        }).then(res => {
          console.log("删除结果：", res);
          if (res.code === 200) {
            Taro.showToast({
              title: "删除成功",
              icon: "success",
              duration: 2000,
            });
            getTaskList();
          }
          else {
            Taro.showToast({
              title: "删除失败",
              icon: "none",
              duration: 2000,
            });
          }
        });
      }
    },
  });
};

const getTaskList = () => {
  const url = getListUrl();
  post(url, {

  }).then(res => {
    console.log("获取任务列表：", res);
  });
};

onMounted(() => {
  getTaskList();
});

// 加载更多
const handleLoadMore = () => {
  Taro.showToast({
    title: "正在加载更多...",
    icon: "loading",
    duration: 1000,
  });
};
//查询请求参数
const queryParams = {
  pageNo: 1,           // 第1页
  pageSize: 10,        // 每页10条
  type: 0,
  status: 0
};
//获取我发布的日结数据
post('/recruitmentDaily/all', queryParams).then(res => {
  publishedItems.value[0] = res.data.map((item) => ({
    member_id: item.columns.member_id,
    publishTime: item.columns.create_time,
    time_frame: item.columns.time_frame,
    pay_number: item.columns.pay_number,
    title: item.columns.position_name,
    desc: item.columns.description,
    type: item.columns.type,
    experience: item.columns.experience,
    amount: item.columns.salary,
    number: item.columns.number,
    pay_status: item.columns.pay_status,
    update_time: item.columns.update_time,
    name: item.columns.name,
    corporate_name: item.columns.corporate_name,
    location: item.columns.location,
    id: item.columns.id,
    deadline: item.columns.deadline,
    statusClass: item.columns.status,
  }));
  //console.log("publishedItems",publishedItems.value[0])
})
</script>
